﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RTW.Core.Controllers;
using RTW.Model;
using RTW.Servers;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;


namespace RTW.Web.Areas.Personal.Controllers
{
    [Area("Personal")]
    public class SuSongController : BaseController
    {
        public PersonalSuSongServers personalSuSongServers;

        public SuSongController()
        {
            personalSuSongServers = new PersonalSuSongServers();
        }

        public IActionResult Lawsuit()
        {
            return View();
        }

        /// <summary>
        /// 获取个人诉讼档案列表
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetAllPersonalSuSongJson(PagingParameter selectParameter, string fileState,string fileClass,string fileNo,string fYear,string fTerm,string caseValue,string dsr)
        {
            //需要 院ID，个人Id
            string dwid = "1";
           var res = await personalSuSongServers.GetAllPersonalSuSongFiles(selectParameter,dwid, fileState,fileClass,fileNo,fYear,fTerm,caseValue,dsr);

            int total = res.total;
            List<PersonalSuSongFilesList> personalSuSongFilesList = res.personalSuSongFileList;

            return Json(ListsResults<PersonalSuSongFilesList>(personalSuSongFilesList, total));
        }

        /// <summary>
        /// From表单的绑定
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> LawsuitForm(int id, string type)
        {
            PersonalSuSongEditModel personalSuSongEditModel = new PersonalSuSongEditModel();
            if (type == "edit")//编辑
            {
                //获取案卷
                personalSuSongEditModel.PersonalSuSongFiles = await personalSuSongServers.GetPersonalSuSongFilesForId(id);
                if (personalSuSongEditModel.PersonalSuSongFiles != null)
                {
                    //获取封面
                    PersonalSuSongCover cover = await personalSuSongServers.GetPersonalSuSongCoverForFilesID(personalSuSongEditModel.PersonalSuSongFiles.FileId);
                    if (cover == null)
                    {
                        cover = new PersonalSuSongCover();
                        cover.Secure = "秘密";
                    }
                    //赋值
                    personalSuSongEditModel.PersonalSuSongCoverForXMS = personalSuSongEditModel.PersonalSuSongCoverForGY = personalSuSongEditModel.PersonalSuSongCoverForXXS = personalSuSongEditModel.PersonalSuSongCoverForJXS = personalSuSongEditModel.PersonalSuSongCoverForJMS = cover;
                }
                else
                {
                    PersonalSuSongCover cover = new PersonalSuSongCover();
                    cover.Secure = "秘密";
                    personalSuSongEditModel.PersonalSuSongCoverForXMS = personalSuSongEditModel.PersonalSuSongCoverForGY = personalSuSongEditModel.PersonalSuSongCoverForXXS = personalSuSongEditModel.PersonalSuSongCoverForJXS = personalSuSongEditModel.PersonalSuSongCoverForJMS = cover;
                }
            }

            ViewData["type"] = type;

            return View(personalSuSongEditModel);
        }

        /// <summary>
        /// 添加和编辑操作
        /// </summary>
        /// <param name="format"></param>
        /// <param name="model">编辑用model</param>
        /// <param name="type">操作类型</param>
        /// <param name="tabsName">案卷类别</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> LawsuitForm(IFormCollection format, PersonalSuSongEditModel model, string type, string tabsName)
        {
            if (type == "add")//添加
            {
                string fileId = Guid.NewGuid().ToString().Replace("-", "");
                string coverId = Guid.NewGuid().ToString().Replace("-", "");

                #region 案卷信息
                PersonalSuSongFiles files = new PersonalSuSongFiles();
                string FType = "";
                if (tabsName == "msss")
                {
                    FType = "民事行政";
                }
                else if (tabsName == "xsss")
                {
                    FType = "刑事诉讼";
                }
                else if (tabsName == "gyss")
                {
                    FType = "公益诉讼";
                }
                files.FileId = fileId;
                files.FType = FType;
                files.NewOrOld = format["NewOrOld"];
                string fyear = format["Fyear"];
                if (!string.IsNullOrWhiteSpace(fyear))
                {
                    try
                    {
                        files.FYear = Convert.ToInt32(fyear);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                files.FTerm = GetFtermForCode(format["FTermCode"]);
                files.FTermCode = format["FTermCode"];
                files.BookType = format["BookType"];
                files.BookNum = format["BookNum"];
                files.AddTime = DateTime.Now;
                files.DWID = 1;
                files.CoverID = coverId;
                files.FilesState = FileState.待提交;

                try
                {
                    int a = await personalSuSongServers.Add(files);
                }
                catch (Exception e)
                {

                    throw e;
                }

                #endregion


                #region 封面信息
                PersonalSuSongCover covermodel = new PersonalSuSongCover();
                covermodel.AddTime = DateTime.Now;
                covermodel.CoverID = coverId;
                covermodel.FilesID = fileId;
                covermodel.KeepingTerm = files.FTerm;
                covermodel.Zhi = format["ZI"];
                covermodel.Hao = format["HAO"];

                if (tabsName == "msss")
                {
                    if (files.NewOrOld == "1")//新卷皮
                    {
                        covermodel.CreatUnit = format["MS_New_CreatUnit"];
                        covermodel.TYSAH = format["MS_New_TYSAH"];
                        covermodel.LaiYuan = format["MS_New_LaiYuan"];
                        covermodel.SQR = format["MS_New_SQR"];
                        covermodel.OtherLitigant = format["MS_New_OtherLitigant"];
                        covermodel.CaseCause = format["MS_New_CaseCause"];
                        covermodel.UnDepart = format["MS_New_UnDepart"];
                        covermodel.LaiYuan = format["MS_New_LaiYuan"];
                        covermodel.Result1 = format["MS_New_Result1"];
                        string pagecount = format["MS_New_PageCount"];
                        if (!string.IsNullOrWhiteSpace(pagecount))
                        {
                            try
                            {
                                covermodel.PageCount = Convert.ToInt32(pagecount);
                            }
                            catch (Exception)
                            {

                                throw;
                            }
                        }
                        covermodel.Secure = format["MS_New_Secure"];
                        covermodel.Undertaker = format["MS_New_Undertaker"];
                        covermodel.ReceiveDate = format["MS_New_ReceiveDate"];
                        covermodel.EndDate = format["MS_New_EndDate"];
                    }
                    else
                    {
                        covermodel.CaseCause = format["MS_Old_CaseCause"];
                        covermodel.LaiYuan = format["MS_Old_LaiYuan"];
                        covermodel.SSR = format["MS_Old_SSR"];
                        covermodel.BSSR = format["MS_Old_BSSR"];
                        covermodel.UnDepart = format["MS_Old_UnDepart"];
                        covermodel.Result1 = format["MS_Old_Result1"];
                        string pagecount = format["MS_Old_PageCount"];
                        if (!string.IsNullOrWhiteSpace(pagecount))
                        {
                            try
                            {
                                covermodel.PageCount = Convert.ToInt32(pagecount);
                            }
                            catch (Exception)
                            {

                                throw;
                            }
                        }
                        covermodel.Secure = format["MS_Old_Secure"];
                        covermodel.Undertaker = format["MS_Old_Undertaker"];
                        covermodel.ReceiveDate = format["MS_Old_ReceiveDate"];
                        covermodel.EndDate = format["MS_Old_EndDate"];
                    }
                }
                else if (tabsName == "gyss")
                {
                    if (files.NewOrOld == "1")//新卷皮
                    {
                        covermodel.CreatUnit = format["GY_New_CreatUnit"];
                        covermodel.TYSAH = format["GY_New_TYSAH"];
                        covermodel.LaiYuan = format["GY_New_LaiYuan"];
                        covermodel.JDDX = format["GY_New_JDDX"];
                        covermodel.CaseCause = format["GY_New_CaseCause"];
                        covermodel.SQCX = format["GY_New_SQCX"];
                        covermodel.Result1 = format["GY_New_Result1"];
                        string pagecount = format["GY_New_PageCount"];
                        if (!string.IsNullOrWhiteSpace(pagecount))
                        {
                            try
                            {
                                covermodel.PageCount = Convert.ToInt32(pagecount);
                            }
                            catch (Exception)
                            {

                                throw;
                            }
                        }
                        covermodel.Secure = format["GY_New_Secure"];
                        covermodel.Undertaker = format["GY_New_Undertaker"];
                        covermodel.ReceiveDate = format["GY_New_ReceiveDate"];
                        covermodel.EndDate = format["GY_New_EndDate"];
                    }
                }
                else if (tabsName == "xsss")
                {
                    if (files.NewOrOld == "1")//新卷皮
                    {
                        covermodel.CreatUnit = format["XS_New_CreatUnit"];
                        covermodel.TYSAH = format["XS_New_TYSAH"];
                        covermodel.LaiYuan = format["XS_New_LaiYuan"];
                        covermodel.SSR = format["XS_New_SSR"];
                        covermodel.FZXYRBGR = format["XS_New_FZXYRBGR"];
                        covermodel.CaseCause = format["XS_New_CaseCause"];
                        covermodel.Result1 = format["XS_New_Result1"];
                        string pagecount = format["XS_New_PageCount"];
                        if (!string.IsNullOrWhiteSpace(pagecount))
                        {
                            try
                            {
                                covermodel.PageCount = Convert.ToInt32(pagecount);
                            }
                            catch (Exception)
                            {

                                throw;
                            }
                        }
                        covermodel.Secure = format["XS_New_Secure"];
                        covermodel.Undertaker = format["XS_New_Undertaker"];
                        covermodel.ReceiveDate = format["XS_New_ReceiveDate"];
                        covermodel.EndDate = format["XS_New_EndDate"];
                    }
                    else
                    {
                        covermodel.LaiYuan = format["XS_Old_LaiYuan"];
                        covermodel.SSR = format["XS_Old_SSR"];
                        covermodel.FZXYRBGR = format["XS_Old_FZXYRBGR"];
                        covermodel.CaseCause = format["XS_Old_CaseCause"];
                        covermodel.Result1 = format["XS_Old_Result1"];
                        string pagecount = format["XS_Old_PageCount"];
                        if (!string.IsNullOrWhiteSpace(pagecount))
                        {
                            try
                            {
                                covermodel.PageCount = Convert.ToInt32(pagecount);
                            }
                            catch (Exception)
                            {

                                throw;
                            }
                        }
                        covermodel.Secure = format["XS_Old_Secure"];
                        covermodel.Undertaker = format["XS_Old_Undertaker"];
                        covermodel.ReceiveDate = format["XS_Old_ReceiveDate"];
                        covermodel.EndDate = format["XS_Old_EndDate"];
                        covermodel.EndDate = format["MS_New_EndDate"];
                    }
                }
                else
                {

                }

                #region 当事人赋值
                string dsr = "";
                if (!string.IsNullOrWhiteSpace(covermodel.FZXYRBGR))
                {
                    dsr = dsr + "犯罪嫌疑人/被告人:" + covermodel.FZXYRBGR + ";";
                }
                if (!string.IsNullOrWhiteSpace(covermodel.SSR))
                {
                    dsr = dsr + "申诉人:" + covermodel.SSR + ";";
                }
                if (!string.IsNullOrWhiteSpace(covermodel.BSSR))
                {
                    dsr = dsr + "被申诉人:" + covermodel.BSSR + ";";
                }
                if (!string.IsNullOrWhiteSpace(covermodel.SQR))
                {
                    dsr = dsr + "申请人:" + covermodel.SQR + ";";
                }
                if (!string.IsNullOrWhiteSpace(covermodel.OtherLitigant))
                {
                    dsr = dsr + "其他当事人:" + covermodel.OtherLitigant + ";";
                }

                covermodel.Litigant = dsr;
                #endregion

                //处理结果
                if (!string.IsNullOrWhiteSpace(covermodel.Result1))
                {
                    if (string.IsNullOrWhiteSpace(covermodel.Result2))
                    {
                        covermodel.Result2 = covermodel.Result1;
                    }
                }
                else
                {
                    covermodel.Result1 = covermodel.Result2;
                }

                int b = await personalSuSongServers.PersonalSuSongCoverAdd(covermodel);
                #endregion

                return Json(MsgResult(b == 1));
            }
            else if (type == "edit")//编辑
            {
                string FType = "";
                if (tabsName == "msss")
                {
                    FType = "民事行政";
                }
                else if (tabsName == "xsss")
                {
                    FType = "刑事诉讼";
                }
                else if (tabsName == "gyss")
                {
                    FType = "公益诉讼";
                }
                string guid = Guid.NewGuid().ToString().Replace("-", "");
                PersonalSuSongFiles tfileModel = await personalSuSongServers.GetPersonalSuSongFilesForId(model.PersonalSuSongFiles.ID);
                model.PersonalSuSongFiles.UserId = tfileModel.UserId;
                model.PersonalSuSongFiles.AddTime = DateTime.Now;
                model.PersonalSuSongFiles.FType = FType;
                model.PersonalSuSongFiles.FilesState = tfileModel.FilesState;
                model.PersonalSuSongFiles.CoverID = guid;
                model.PersonalSuSongFiles.DWID = tfileModel.DWID;
                model.PersonalSuSongFiles.FileId = tfileModel.FileId;
                model.PersonalSuSongFiles.FTerm = GetFtermForCode(model.PersonalSuSongFiles.FTermCode);
                int a = await personalSuSongServers.Edit(model.PersonalSuSongFiles);

                PersonalSuSongCover coverModel = new PersonalSuSongCover();
                if (tabsName == "msss")
                {
                    if (model.PersonalSuSongFiles.NewOrOld == "1")
                    {
                        coverModel = model.PersonalSuSongCoverForXMS;
                    }
                    else
                    {
                        coverModel = model.PersonalSuSongCoverForJMS;
                    }
                }
                else if (tabsName == "gyss")
                {
                    coverModel = model.PersonalSuSongCoverForGY;
                }
                else if (tabsName == "xsss")
                {
                    if (model.PersonalSuSongFiles.NewOrOld == "1")
                    {
                        coverModel = model.PersonalSuSongCoverForXXS;
                    }
                    else
                    {
                        coverModel = model.PersonalSuSongCoverForJXS;
                    }
                }

                coverModel.CoverID = guid;
                coverModel.FilesID = model.PersonalSuSongFiles.FileId;
                coverModel.AddTime = DateTime.Now;
                coverModel.KeepingTerm = model.PersonalSuSongFiles.FTerm;

                #region 当事人赋值
                string dsr = "";
                if (!string.IsNullOrWhiteSpace(coverModel.FZXYRBGR))
                {
                    dsr = dsr + "犯罪嫌疑人/被告人:" + coverModel.FZXYRBGR + ";";
                }
                if (!string.IsNullOrWhiteSpace(coverModel.SSR))
                {
                    dsr = dsr + "申诉人:" + coverModel.SSR + ";";
                }
                if (!string.IsNullOrWhiteSpace(coverModel.BSSR))
                {
                    dsr = dsr + "被申诉人:" + coverModel.BSSR + ";";
                }
                if (!string.IsNullOrWhiteSpace(coverModel.SQR))
                {
                    dsr = dsr + "申请人:" + coverModel.SQR + ";";
                }
                if (!string.IsNullOrWhiteSpace(coverModel.OtherLitigant))
                {
                    dsr = dsr + "其他当事人:" + coverModel.OtherLitigant + ";";
                }

                coverModel.Litigant = dsr;

                #endregion

                //处理结果
                if (!string.IsNullOrWhiteSpace(coverModel.Result1))
                {
                    if (string.IsNullOrWhiteSpace(coverModel.Result2))
                    {
                        coverModel.Result2 = coverModel.Result1;
                    }
                }
                else
                {
                    coverModel.Result1 = coverModel.Result2;
                }

                int b = await personalSuSongServers.PersonalSuSongCoverAdd(coverModel);

                return Json(MsgResult(b == 1));
            }

            return View();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> del(string ids)
        {
            int res = await personalSuSongServers.PersonalSuSongFilesDel(ids);
            return Json(res);
        }

        public IActionResult Directory(string id)
        {
            //根据案卷id获取卷内目录
            ViewData["fileid"] = id;
            return View();
        }

        /// <summary>
        /// 根据案卷id获取卷内目录
        /// </summary>
        /// <param name="id">案卷id</param>
        /// <returns></returns>
        public async Task<string> GetDirectoryJson(string id)
        {
            var res = await personalSuSongServers.GetDirectoryForFileId(id);
            string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(res);
            return jsonStr;
        }

        /// <summary>
        /// 根据案卷id保存卷内目录
        /// </summary>
        /// <param name="id">案卷id</param>
        /// <param name="directorys">table数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> AddDirectoryForFileId(string fileId, string  directorys)
        {
            //.net core 中不存在System.Runtime.Serialization.Json与System.Web.Script.Serialization这两个namespace,
            //因此也就不存在JavaScriptSerializer，所以在移植项目时，可以使用Newtonsoft.Json中的JsonConvert来替代。
            //.net framework下
            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //var res = serializer.Serialize(YourObject);
            //.net core 下使用Newtonsoft.Json
            // var res = JsonConvert.SerializeObject(YourObject);

            //接收到的数据转化为对象
            List<PersonalSuSongDirectory> directoryList = new List<PersonalSuSongDirectory>();
            try
            {
                //json转object
                directoryList = JsonConvert.DeserializeObject<List<PersonalSuSongDirectory>>(directorys);
                if (directoryList.Count>0)
                {
                    #region  先获取原数据的id，插入成功后，删除原数据
                    //根据案卷id获取所属卷内目录
                    var ids = "";
                    var res = await personalSuSongServers.GetDirectoryForFileId(fileId);
                    for (int i = 0; i < res.Count; i++)
                    {
                        if (i==0)
                        {
                            ids = res[i].ID;
                        }
                        else
                        {
                            ids = ids + "," + res[i].ID;
                        }
                    }

                    //循环插入数据
                    for (int i = 0; i < directoryList.Count; i++)
                    {
                        PersonalSuSongDirectory directory = new PersonalSuSongDirectory();

                        directory = directoryList[i];
                        directory.FilesID = fileId;
                        int b = await personalSuSongServers.PersonalSuSongCoverAdd(directory);
                    }

                    //插入完成，删除原来数据
                    if (!string.IsNullOrWhiteSpace(ids))
                    {
                        int b = await personalSuSongServers.PersonalSuSongDirectoryDel(ids);
                    }
                    #endregion
                }
            }
            catch (Exception e)
            {
                return e.Message;
            }

            return "1";
        }

        /// <summary>
        ///根据期限代码获取期限 
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetFtermForCode(string code)
        {
            string fterm = "";

            switch (code)
            {
                case "1": fterm = "永久"; break;
                case "2": fterm = "60年"; break;
                case "3": fterm = "30年"; break;
                case "Y": fterm = "永久"; break;
                case "C": fterm = "60年"; break;
                case "D": fterm = "30年"; break;
                default: fterm = ""; break;
            }
            return fterm;
        }
    }
}